from PIL import Image, ImageDraw, ImageFont
import os

# 确保目录存在
os.makedirs('static/images/products', exist_ok=True)

# 商品信息
products = [
    ('eco_bag.jpg', '环保购物袋', '#87CEEB'),
    ('steel_straw.jpg', '不锈钢吸管', '#90EE90'),
    ('canvas_bag.jpg', '帆布包', '#FFB6C1'),
    ('bamboo_cutlery.jpg', '竹制餐具', '#DDA0DD'),
    ('glass_cup.jpg', '玻璃水杯', '#F0E68C')
]

def create_product_image(filename, text, color):
    # 创建图片
    img = Image.new('RGB', (400, 300), color)
    draw = ImageDraw.Draw(img)
    
    # 添加文字
    try:
        # 尝试使用系统字体
        font = ImageFont.truetype("simhei.ttf", 32)
    except:
        # 如果找不到中文字体，使用默认字体
        font = ImageFont.load_default()
    
    # 计算文字位置使其居中
    text_bbox = draw.textbbox((0, 0), text, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]
    
    x = (400 - text_width) // 2
    y = (300 - text_height) // 2
    
    # 绘制文字
    draw.text((x, y), text, fill='black', font=font)
    
    # 保存图片
    img.save(f'static/images/products/{filename}')
    print(f'已创建: {filename}')

# 创建所有商品图片
for filename, text, color in products:
    create_product_image(filename, text, color)

print('所有商品图片已创建完成！') 